package com.decent.ejfadmin.finance.controller;

import com.decent.ejfadmin.common.bean.MessageBean;
import com.decent.ejfadmin.common.bean.Page;
import com.decent.ejfadmin.common.bean.WithdrawLog;
import com.decent.ejfadmin.common.bean.WithdrawRecord;
import com.decent.ejfadmin.common.enums.WithdrawLogTypeEnum;
import com.decent.ejfadmin.common.exception.SupException;
import com.decent.ejfadmin.finance.request.RebateUserQueryParam;
import com.decent.ejfadmin.finance.request.WithdrawRecordQueryParam;
import com.decent.ejfadmin.finance.response.dto.WithdrawRecordDto;
import com.decent.ejfadmin.finance.service.SupplyFinanceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 财务管理
 *
 * @author zhangchao
 * @date 2018/7/27 14:44
 */
@Slf4j
@RestController
@RequestMapping("finance")
public class SupplyFinanceController {

    @Autowired
    private SupplyFinanceService supplyFinanceService;

    /**
     * 查询提现记录分页数据
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "findWithdrawRecordPage")
    public Page findWithdrawRecordPage(WithdrawRecordQueryParam param) {
        Page page = new Page();
        try {
            page = supplyFinanceService.findWithdrawRecordPage(param);
        } catch (Exception e) {
            page.setTotal(0);
            log.warn("SupplyFinanceController findWithdrawRecordPage occurs error Internal Server Error  ", e);
        }
        return page;
    }

    /**
     * 审核提现记录
     *
     * @param recordId
     * @param auditstate
     * @return
     */
    @RequestMapping(value = "checkWithdrawRecord", method = RequestMethod.POST)
    public MessageBean checkWithdrawRecord(Long recordId, Integer auditstate) {
        try {
            return supplyFinanceService.checkWithdrawRecord(recordId, auditstate);
        } catch (SupException e) {
            log.warn("SupplyFinanceController checkWithdrawRecord occurs error " + e.getResMessage());
            return MessageBean.fail(e.getResMessage());
        } catch (Exception e) {
            log.warn("SupplyFinanceController checkWithdrawRecord occurs error Internal Server Error  ", e);
            return MessageBean.fail();
        }
    }

    /**
     * 再次转账
     *
     * @param recordId
     * @return
     */
    @RequestMapping(value = "resetTransfer", method = RequestMethod.POST)
    public MessageBean resetTransfer(Long recordId) {
        MessageBean messageBean = MessageBean.success();
        try {
            supplyFinanceService.resetTransfer(recordId);
        } catch (SupException e) {
            messageBean = MessageBean.fail(e.getResMessage());
            log.warn("SupplyFinanceController resetTransfer occurs error " + e.getResMessage());
        } catch (Exception e) {
            messageBean = MessageBean.fail();
            log.warn("SupplyFinanceController resetTransfer occurs error Internal Server Error  ", e);
        }
        return messageBean;
    }

    /**
     * 处理失败
     *
     * @param recordId
     * @return
     */
    @RequestMapping(value = "dealFail", method = RequestMethod.POST)
    public MessageBean dealFail(Long recordId) {
        MessageBean messageBean = MessageBean.success();
        try {
            supplyFinanceService.dealFail(recordId);
        } catch (SupException e) {
            messageBean = MessageBean.fail(e.getResMessage());
            log.warn("SupplyFinanceController dealFail occurs error " + e.getResMessage());
        } catch (Exception e) {
            messageBean = MessageBean.fail();
            log.warn("SupplyFinanceController dealFail occurs error Internal Server Error  ", e);
        }
        return messageBean;
    }

    /**
     * 自动审核开关 1:开启自动  0：关闭自动
     *
     * @param status
     * @return
     */
    @RequestMapping(value = "changeAutoAuditStatus", method = RequestMethod.POST)
    public MessageBean changeAutoAuditStatus(Integer status) {
        MessageBean messageBean = MessageBean.success();
        try {
            supplyFinanceService.changeAutoAuditStatus(status);
        } catch (SupException e) {
            messageBean = MessageBean.fail(e.getResMessage());
            log.warn("SupplyFinanceController changeAutoAuditStatus occurs error " + e.getResMessage());
        } catch (Exception e) {
            messageBean = MessageBean.fail();
            log.warn("SupplyFinanceController changeAutoAuditStatus occurs error Internal Server Error  ", e);
        }
        return messageBean;
    }

    /**
     * 查询返利用户信息统计分页数据
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "findRebateUserPage", method = RequestMethod.GET)
    public Page findRebateUserPage(RebateUserQueryParam param) {
        Page page = new Page();
        try {
            page = supplyFinanceService.findRebateUserPage(param);
        } catch (Exception e) {
            page.setTotal(0);
            log.warn("SupplyFinanceController findRebateUserPage occurs error Internal Server Error  ", e);
        }
        return page;
    }

    /**
     * 自动审核获取状态 true 自动 false 手动
     *
     * @return
     */
    @RequestMapping(value = "getAutoAuditStatus")
    public boolean getAutoAuditStatus() {
        try {
            return supplyFinanceService.getAutoAuditStatus();
        } catch (Exception e) {
            log.warn("SupplyFinanceController findRebateUserPage occurs error Internal Server Error  ", e);
            return true;
        }
    }

    /**
     * 分页查询供货日报表
     *
     * @param pageUnit    分页组件
     * @param startTime   查询开始时间
     * @param endTime     查询结束时间
     * @param userAccount 会员编号
     * @return list
     */
    @RequestMapping(value = "querySupplyDailySheetPage", method = RequestMethod.GET)
    public Page querySupplyDailySheetPage(Page pageUnit, String startTime, String endTime, String userAccount) {
        try {
            return supplyFinanceService.querySupplyDailySheetPage(pageUnit, startTime, endTime, userAccount);
        } catch (Exception e) {
            log.warn("分页查询日报表异常[{}]  ", e);
            pageUnit.setResultList(new ArrayList<>());
            pageUnit.setTotal(0);
            return pageUnit;
        }
    }

    /**
     * 供货日报表导出
     *
     * @param startTime   查询开始时间
     * @param endTime     查询结束时间
     * @param userAccount 会员编号
     * @return
     */
    @RequestMapping("dailyReportdownLoad")
    public void dailyReportdownLoad(String startTime, String endTime, String userAccount, HttpServletResponse response) {
        ServletOutputStream writer = null;
        try {
            response.setCharacterEncoding("GBK");
            response.setContentType("text/html;charset=GBK");
            writer = response.getOutputStream();
            if (org.apache.commons.lang.StringUtils.isBlank(startTime) || org.apache.commons.lang.StringUtils.isBlank(endTime)) {
                String msg = "<script >alert('输入起始时间！');</script>";
                IOUtils.write(msg.getBytes("GBK"), writer);
                writer.flush();
                return;
            }
            supplyFinanceService.downLoad(startTime, endTime, userAccount, response);
        } catch (Exception e) {
            log.warn("供货日报表导出出错[{}]", e);
        } finally {
            IOUtils.closeQuietly(writer);
        }
    }

    /**
     * 会员提现记录导出
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "withdrawRecordDownLoad")
    public void withdrawRecordDownLoad(WithdrawRecordQueryParam param, HttpServletResponse response) {
        ServletOutputStream writer = null;
        try {
            response.setCharacterEncoding("GBK");
            response.setContentType("text/html;charset=GBK");
            writer = response.getOutputStream();
            if (org.apache.commons.lang.StringUtils.isBlank(param.getStartTime()) || org.apache.commons.lang.StringUtils.isBlank(param.getEndTime())) {
                String msg = "<script >alert('输入起始时间！');</script>";
                IOUtils.write(msg.getBytes("GBK"), writer);
                writer.flush();
                return;
            }
            supplyFinanceService.withdrawRecordDownLoad(param, response);
        } catch (Exception e) {
            log.warn("会员提现记录导出出错[{}]", e);
        } finally {
            IOUtils.closeQuietly(writer);
        }
    }

    /**
     * 对异常、申请中状态的申请人工更改其状态
     *
     * @param withdrawRecord 提现类
     * @param oldState       页面订单提现状态
     * @return
     */
    @RequestMapping("updateWithdrawState")
    public MessageBean updateWithdrawState(WithdrawRecord withdrawRecord, Integer oldState) {
        try {
            if (withdrawRecord == null) {
                return MessageBean.fail("未选择对象");
            }
            if (withdrawRecord.getId() == null) {
                return MessageBean.fail("请选择要操作的记录");
            }
            if (withdrawRecord.getState() == null) {
                return MessageBean.fail("请选择状态");
            }
            if (oldState == null) {
                return MessageBean.fail("未获取到当前状态!");
            }
            return supplyFinanceService.updateWithdrawState(withdrawRecord, oldState);
        } catch (Exception e) {
            log.warn("更改提现状态失败", e);
            return MessageBean.fail();
        }
    }

    /**
     * 停止/开启自动开启自动审核获取状态
     *
     * @param status 0:启动  1:停止
     * @return
     */
    @RequestMapping(value = "stopOpenAutoAudit", method = RequestMethod.POST)
    public MessageBean stopOpenAutoAudit(Integer status) {
        try {
            return supplyFinanceService.stopOpenAutoAudit(status);
        } catch (Exception e) {
            log.warn("停止自动开启自动审核失败", e);
            return MessageBean.fail();
        }
    }

    /**
     * 停止自动开启自动审核获取状态 true 已停止
     *
     * @return
     */
    @RequestMapping(value = "getStopOpenAutoAudit")
    public boolean getStopOpenAutoAudit() {
        try {
            return supplyFinanceService.getStopOpenAutoAudit();
        } catch (Exception e) {
            log.warn("SupplyFinanceController getStopOpenAutoAudit occurs error Internal Server Error{}  ", e, e);
            return true;
        }
    }

    /**
     * 查询提现记录操作日志
     *
     * @param withdrawId 提现Id
     * @return 返回信息
     */
    @RequestMapping("queryWithdrawrLog")
    public List<WithdrawLog> queryWithdrawrLog(Long withdrawId, WithdrawLogTypeEnum type) {
        try {
            if (withdrawId == null || type == null) {
                return new ArrayList<>(0);
            }
            return supplyFinanceService.queryWithdrawLog(withdrawId, type);
        } catch (Exception e) {
            log.warn(" [{}]操作记录查询异常{}", withdrawId, e, e);
            return new ArrayList<>(0);
        }
    }

    /**
     * 查询会员提现明细
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "findWithdrawRecord")
    public List<WithdrawRecordDto> findWithdrawRecord(WithdrawRecordQueryParam param) {
        try {
            return supplyFinanceService.findWithdrawRecord(param);
        } catch (Exception e) {
            log.warn(" [{}]查询会员提现明细异常[{}]", param, e.getMessage(), e);
            return Collections.emptyList();
        }
    }
}
